<?php
/**
 * PHP version 5
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    Textbook
 * @subpackage User
 * @author     Aljaz Srebrnic <a2piratesoft@gmail.com>
 * @author     E. Pavletič
 * @copyright  2008 a2PirateSoftware
 * @license    GPL License v3 <http://www.gnu.org/copyleft/gpl.html>
 */

require_once("class.CommonAction.php");
require_once(ZNF::MODULES_DIR.'/User/Business/UserDAO.php');
require_once(ZNF::MODULES_DIR.'/User/Business/RoleDAO.php');
require_once('ZNF/Presentation/Smarty.php');

class User_Action_Register extends CommonAction {

    private $userDao;
    private $roleDao;

    public function __construct(){
        parent::__construct();
        $this->userDao = new User_Business_UserDAO();
        $this->roleDao = new User_Business_RoleDAO();
    }

    /**
     *Metoda prikaze form za vpis novega uporabnika ali za spreminjanje podatkov ze logiranega uporabnika.
    */

    public function display($form, ZNF_Action_ActionMapping $mapping)
    {
        $_REQUEST['key'] = self::sendToken(true);
        if($_SESSION['znf']['authenticated'] == true)
        {
            try{
                $user = $this->userDao->getById($_SESSION['id']);
            } catch(User_Business_UserDAOException $e){
                $_REQUEST['errors'] = self::handleException($e, 'User');
                return $mapping->findForward('failure');
            }
            $_REQUEST['user'] = $user;
        }
        $this->logger->debug('Registration form sent');
        return $mapping->findForward('success');
    }

    /**
     *Metoda prejme izpolnjen form in doda uporabnika v bazo podatkov.
    */

    public function register(ZNF_action_ActionForm $form, ZNF_Action_ActionMapping $mapping)
    {
        $smarty = new ZNF_Presentation_Smarty('User', $mapping);
	$translation = new ZNF_Presentation_Translation('User', $_SESSION['znf']['lang']);

        $pwd = htmlspecialchars(addslashes(self::generatePassword()));
        $this->logger->debug('['.__METHOD__.':'.__LINE__.'] -password generated.');
        try{
            $this->userDao->insert($form->getUsername(), $pwd, $form->getName(), $form->getSurname(),
                                   $form->getPhone(), $form->getCell(), $form->getEmail(), $form->getIcq(),
                                   $form->getMsn(), $form->getSkype());

        }catch(User_Business_UserDAOException $e)
        {
            $_REQUEST['errors'] = self::handleException($e, 'User');
            return $mapping->findForward('failure');
        }
        $this->logger->debug('['.__METHOD__.':'.__LINE__.'] - User inserted into database.');

        $smarty->assign('name', $form->getName());
        $smarty->assign('surname', $form->getSurname());
        $smarty->assign('username', $form->getUsername());
        $smarty->assign('password', $pwd);

	$this->logger->debug('['.__METHOD__.':'.__LINE__.'] - Sending email');
        try{
            $this->sendEmail($form->getName(), $form->getSurname(), $form->getEmail(),
                             $translation->get('newUserEmailSubject'), $smarty->fetch("email.tpl"));
        } catch (ZNF_Action_ActionException $e)
        {
            $_REQUEST['errors'] = self::handleException($e, 'User');
            return $mapping->findForward('failure');
        }
        $this->logger->debug('['.__METHOD__.':'.__LINE__.'] - Email sent to user.');
        return $mapping->findForward('success');
    }



    /**
     *Metoda poslje novo geslo uporabniku
     **/
    public function recoveryForm($form, ZNF_Action_ActionMapping $mapping){
	if($_SESSION['znf']['authenticated']){
	    $_REQUEST['error'] = self::handleException(new Exception('errorUserAlreadyLoggedIn'), 'User');
	    return $mapping->findForward('failure');
	}
	$this->logger->debug('['.__METHOD__.':'.__LINE__.'] - Generating key.');
	$_REQUEST['key'] = self::sendToken(true);
	return $mapping->findForward('success');
    }



    public function recovery(ZNF_Action_ActionForm $form, ZNF_Action_ActionMapping $mapping){
		$smarty = new ZNF_Presentation_Smarty('User', $mapping);
		$translation = new ZNF_Presentation_Translation('User', $_SESSION['znf']['lang']);
		try{
		    $userData = $this->userDao->getByUsername($form->getUsername());

		    if($userData['email'] != $form->getEmail())
		        throw new Exception('errorUsernameEmailMismatch');

		    $pwd = htmlspecialchars(addslashes(self::generatePassword()));
		    $this->logger->debug('['.__METHOD__.':'.__LINE__.'] -password generated.');

		    $this->userDao->updatePassword($form->getUsername(), $pwd);
		    $this->logger->debug('['.__METHOD__.':'.__LINE__.'] -password updated.');
		}catch (Exception $e){
		    $_REQUEST['errors'] = self::handleException($e, 'User');
		    return $mapping->findForward('failure');
		}

		$smarty->assign('name', $userData['name']);
	    $smarty->assign('surname', $userData['surname']);
	    $smarty->assign('username', $form->getUsername());
	    $smarty->assign('password', $pwd);
		$smarty->assign('ip', $_SERVER['REMOTE_ADDR']);

		try{
	            $this->sendEmail($userData['name'], $userData['surname'], $userData['email'],
	                             $translation->get('pwdForgotEmailSubject'), $smarty->fetch("recoveryEmail.tpl"));
        } catch (ZNF_Action_ActionException $e) {
            $_REQUEST['errors'] = self::handleException($e, 'User');
            return $mapping->findForward('failure');
        }
        $this->logger->debug('['.__METHOD__.':'.__LINE__.'] - Email sent to user.');
		$_REQUEST['value'] = true;
        return $mapping->findForward('success');
    }

    /**
     *Metoda posodobi podatke o uporabniku.
     **/

    public function update(ZNF_Action_ActionForm $form, ZNF_Action_ActionMapping $mapping){
        try{
            $this->userDao->update($_SESSION['id'], $form->getName(), $form->getSurname(),
                                   $form->getPhone(), $form->getCell(), $form->getEmail(), $form->getIcq(),
                                   $form->getMsn(), $form->getSkype());
        }catch(User_Business_UserDAOException $e){
            $_REQUEST['errors'] = self::handleException($e, 'User');
            return $mapping->findForward('failure');
        }
        return $mapping->findForward('success');
    }

    /**
     *Metoda preveri, ali je uporabnisko ime ze zasedeno.
     **/

    public function checkUsername(ZNF_Action_ActionForm $form, ZNF_Action_ActionMapping $mapping)
    {
        try{
            $ret = $this->userDao->check($form->getUsername());
        }catch (User_Business_UserDAOException $e)
        {
            $_REQUEST['errors'] = self::handleException($e, 'User');
            return $mapping->findForward('failure');
        }
        $_REQUEST['value'] = $ret;
        return $mapping->findForward('success');
    }
}

?>